package com.bdth.bdthiss.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.bdth.bdthiss.entity.Brand;
import com.bdth.bdthiss.entity.Brands;
import com.bdth.bdthiss.entity.Warrant;
import com.bdth.bdthiss.jsoup.FileTools;
import com.bdth.bdthiss.service.BrandService;
import com.bdth.bdthiss.service.BrandsService;
import com.bdth.bdthiss.service.WarrantService;
import com.bdth.bdthiss.vo.MessageResult;
import com.bdth.bdthiss.vo.PageVo;
import com.bdth.bdthiss.vo.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LGP
 * @since 2020-04-14
 */
@Controller
@RequestMapping("/warrant")
public class WarrantController {
    @Autowired
    public WarrantService warrantService;

    @Autowired
    public BrandService brandService;

    @Autowired
    public BrandsService brandsService;

    @Autowired
    private Environment env;

    @RequestMapping("index")
    public String index(){
        return "warrant/index";
    }

    @RequestMapping("form")
    public String form(){
        return "warrant/form";
    }

    @RequestMapping("search")
    public String search(){
        return "warrant/search";
    }

    @RequestMapping("warring")
    public String warring(){
        return "warrant/warring";
    }

    @RequestMapping(value = "list")
    @ResponseBody
    public PageVo<Warrant> getPageList(Pagination<Warrant> pagination,Warrant param){
        Map<String,Object> query = new HashMap<>();
        if(param!=null &&param.getCompanyname()!=null){
            query.put("companyname",param.getCompanyname());
        }
        if(param!=null &&param.getBrandname()!=null){
            query.put("brandname",param.getBrandname());
        }
        if(param!=null &&param.getRegion()!=null){
            query.put("region",param.getRegion());
        }
        Page<Warrant> items = warrantService.listPages(pagination,query);
        PageVo<Warrant> pageVo = new PageVo<>(items.getRecords(),items.getTotal());
        return pageVo;
    }

    @RequestMapping(value = "save")
    @ResponseBody
    public MessageResult save(Warrant param,@RequestParam(value="pic")MultipartFile file){
        fileUpload(param,file);
        String brandnames = param.getBrandname();
        String[] brandnameList =brandnames.split("、");
        for(String brandname:brandnameList){
            insertBrand(brandname);
        }
        warrantService.insert(param);
        return MessageResult.getSuccess("添加成功");
    }

    @RequestMapping(value = "update")
    @ResponseBody
    public MessageResult update(Warrant param,@RequestParam(value="pic")MultipartFile file){
        fileUpload(param,file);
        String brandnames = param.getBrandname();
        String[] brandnameList =brandnames.split("、");
        for(String brandname:brandnameList){
            insertBrand(brandname);
        }
        warrantService.updateById(param);
        return MessageResult.getSuccess("修改成功");
    }

    /**
     * 添加新的品牌信息
     */
    public void insertBrand(String brandname){
        EntityWrapper<Brand> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("name",brandname);
        List<Brand> brandList = brandService.selectList(entityWrapper);
        int brandid = 0;
        if(brandList!=null && brandList.size()>0) {
            return;
        }
        Brand bean = new Brand();
        bean.setName(brandname);
        bean.setHash(0);
        bean.setSort(0);
        brandService.insert(bean);
        brandid = bean.getId();
        Brands temp = new Brands();
        temp.setBrandid(brandid);
        temp.setCnname(bean.getName());
        brandsService.insert(temp);
    }

    private void fileUpload(Warrant param,MultipartFile file){
        // 先设定一个放置上传文件的文件夹(该文件夹可以不存在，下面会判断创建)
        String deposeFilesDir = env.getProperty("data.save.where")+"warrant\\";
        // 判断文件手否有内容
        if (file.isEmpty()) {
            System.out.println("该文件无任何内容!!!");
        }else {
            // 获取附件原名(有的浏览器如chrome获取到的是最基本的含 后缀的文件名,如myImage.png)
            // 获取附件原名(有的浏览器如ie获取到的是含整个路径的含后缀的文件名，如C:\\Users\\images\\myImage.png)
            String fileName = file.getOriginalFilename();
            // 如果是获取的含有路径的文件名，那么截取掉多余的，只剩下文件名和后缀名
            int index = fileName.lastIndexOf("\\");
            if (index > 0) {
                fileName = fileName.substring(index + 1);
            }
            // 当文件有后缀名时
            if (fileName.indexOf(".") >= 0) {
                // split()中放正则表达式; 转义字符"\\."代表 "."
                String[] fileNameSplitArray = fileName.split("\\.");
                // 加上random戳,防止附件重名覆盖原文件
                fileName = fileNameSplitArray[0] + (int) (Math.random() * 100000) + "." + fileNameSplitArray[1];
            }
            // 当文件无后缀名时(如C盘下的hosts文件就没有后缀名)
            if (fileName.indexOf(".") < 0) {
                // 加上random戳,防止附件重名覆盖原文件
                fileName = fileName + (int) (Math.random() * 100000);
            }
            System.out.println("fileName:" + fileName);
            param.setPicaddress("upload/warrant/"+fileName);
            // 根据文件的全路径名字(含路径、后缀),new一个File对象dest
            File dest = new File(deposeFilesDir + fileName);
            // 如果该文件的上级文件夹不存在，则创建该文件的上级文件夹及其祖辈级文件夹;
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                // 将获取到的附件file,transferTo写入到指定的位置(即:创建dest时，指定的路径)
                file.transferTo(dest);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("文件的全路径名字(含路径、后缀)>>>>>>>" + deposeFilesDir + fileName);
        }
    }

    @RequestMapping(value = "delete")
    @ResponseBody
    public MessageResult delete(@RequestParam Integer ids){
        warrantService.deleteById(ids);
        return MessageResult.getSuccess("数据已删除");
    }

    @RequestMapping(value = "remove")
    @ResponseBody
    public MessageResult deletes(@RequestParam String ids){
        String[] id = ids.split(",");
        for (String i: id) {
            Integer intId = Integer.parseInt(i);
            warrantService.deleteById(intId);
        }
        return MessageResult.getSuccess("数据已删除");
    }
    @RequestMapping(value = "image")
    public ModelAndView image(HttpServletResponse response){
        ModelAndView mv = new ModelAndView();
        // 先设定一个放置上传文件的文件夹(该文件夹可以不存在，下面会判断创建)
        String deposeFilesDir = env.getProperty("data.save.where")+"warrant\\";
        //图片url
        String url = env.getProperty("data.save.url");
        List<String> filenames = FileTools.getDirFilesName(url,new File(deposeFilesDir));
        mv.addObject("filenames",filenames);
        mv.setViewName("warrant/image");
        return mv;
    }
}

